package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.bean.RukuSuccessBean;
import com.example.administrator.printoutindemo.di.component.DaggerRuKuChengGongJiLuWuLiaoTuPianComponent;
import com.example.administrator.printoutindemo.di.module.RuKuChengGongJiLuWuLiaoTuPianModule;
import com.example.administrator.printoutindemo.mvp.contract.RuKuChengGongJiLuWuLiaoTuPianContract;
import com.example.administrator.printoutindemo.mvp.presenter.RuKuChengGongJiLuWuLiaoTuPianPresenter;
import com.example.administrator.printoutindemo.mvp.ui.adapter.RuKuChengGongJiLuTuPianGridImageAdapter;
import com.example.administrator.printoutindemo.mvp.ui.entity.RuKuChengGongJiLuWuLiaoTuPian;
import com.example.administrator.printoutindemo.view.FullyGridLayoutManager;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.xiaoxing.zhinenghuacangku.mvp.ui.utils.LogWriter;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_RU_KU_CHENG_GONG_JI_LU_WU_LIAO_TU_PIAN)
public class RuKuChengGongJiLuWuLiaoTuPianActivity extends BaseActivity<RuKuChengGongJiLuWuLiaoTuPianPresenter> implements RuKuChengGongJiLuWuLiaoTuPianContract.View, RuKuChengGongJiLuTuPianGridImageAdapter.IRuKuChengGongJiLuTuPianGridImageAdapter {

    @BindView(R.id.btn_shang_chuang_zhao_pian)
    Button btnShangChuangZhaoPian;
    private RukuSuccessBean mRukuSuccessBean;
    private int maxSelectNum = 10;//最多到几张还可以选择
    private List<LocalMedia> selectList = new ArrayList<>();
    private RuKuChengGongJiLuTuPianGridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;
    private RuKuChengGongJiLuTuPianGridImageAdapter.onAddPicClickListener onAddPicClickListener = new RuKuChengGongJiLuTuPianGridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            showPop();
        }
    };

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerRuKuChengGongJiLuWuLiaoTuPianComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .ruKuChengGongJiLuWuLiaoTuPianModule(new RuKuChengGongJiLuWuLiaoTuPianModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_ru_ku_cheng_gong_ji_lu_wu_liao_tu_pian; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    private LogWriter mLogWriter;

    public void log111(String msg) {

        try {
            mLogWriter.print(RuKuChengGongJiLuWuLiaoTuPianActivity.class, msg);
        } catch (Exception e) {
        }
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_ru_ku_cheng_gong_ji_lu_wu_liao_tu_pian));
        //getRuKuChengGongJiLuWuLiaoTuPianData();
        File logf = new File(Environment.getExternalStorageDirectory() + File.separator + "rukuchenggongjilutupian.txt");
        try {
            mLogWriter = LogWriter.open(logf.getAbsolutePath());
        } catch (Exception e) {
        }
        mRukuSuccessBean = (RukuSuccessBean) getIntent().getExtras().getSerializable("item");

        mRecyclerView = findViewById(R.id.recycler);
        initWidget();


        if (mRukuSuccessBean != null && mRukuSuccessBean.getUppic() != null && mRukuSuccessBean.getUppic().size() > 0) {

            List<LocalMedia> images = new ArrayList<>();


            for (int i = 0; i < mRukuSuccessBean.getUppic().size(); i++) {

                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(mRukuSuccessBean.getUppic().get(i));
                images.add(localMedia);
            }


            selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
            // LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
            adapter.setList(selectList);
            adapter.notifyDataSetChanged();
        }
    }

    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new RuKuChengGongJiLuTuPianGridImageAdapter(getContext(), onAddPicClickListener, this);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new RuKuChengGongJiLuTuPianGridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this).externalPicturePreview(position, "../.../", selectList);
                            PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    @Override
    public void getRuKuChengGongJiLuWuLiaoTuPianDataSuccess(RuKuChengGongJiLuWuLiaoTuPian entityData) {


    }

    private void getRuKuChengGongJiLuWuLiaoTuPianData() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getRuKuChengGongJiLuWuLiaoTuPianData(map);
    }

    private void showPop() {
        View bottomView = View.inflate(RuKuChengGongJiLuWuLiaoTuPianActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .enableCrop(true)
                                .cropWH(300, 300)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //拍照
                        PictureSelector.create(RuKuChengGongJiLuWuLiaoTuPianActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .enableCrop(true)
                                .cropWH(300, 300)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 清空图片缓存，包括裁剪、压缩后的图片，避免OOM
     * 注意:必须要在上传完成后调用 必须要获取权限
     */
    private void clearCache() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    //清除缓存
                    PictureFileUtils.deleteCacheDirFile(RuKuChengGongJiLuWuLiaoTuPianActivity.this);
                } else {
                    Toast.makeText(RuKuChengGongJiLuWuLiaoTuPianActivity.this, getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    public void delImg(int position) {
        try {
            delInstorepic(position);
        } catch (Exception e) {
            e.printStackTrace();
            hideLoading();
        }
    }

    private void delInstorepic(int position) {

        showLoading();

        String methodName = "DelInstorepic";

        SoapParams params = new SoapParams();
        params.put("mid", String.valueOf(mRukuSuccessBean.getMid()));//用户id
        params.put("instoreUppidId", String.valueOf(mRukuSuccessBean.getInstoreUppidId().get(position)));//项目名称


        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    showMessage("图片删除成功");
                    EventBus.getDefault().post("", "updateRuKuChengGongJiLu");

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());

    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R.id.btn_shang_chuang_zhao_pian)
    public void onViewClicked() {
        try {
            List<String> imgs = new ArrayList<>();
            for (int i = 0; i < selectList.size(); i++) {
                if (!selectList.get(i).getPath().contains("http://")) {
                    imgs.add(ArmsUtils.bitmapToString(selectList.get(i).getPath()));
//                    log111(ArmsUtils.bitmapToString(selectList.get(i).getPath()));
                }
            }
            addInstorepic(imgs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addInstorepic(List<String> imgStrs) {

        showLoading();

        String methodName = "AddInstorepic";

        SoapParams params = new SoapParams();
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("mid", String.valueOf(mRukuSuccessBean.getMid()));
        JSONArray jsonArray = (JSONArray) JSON.toJSON(imgStrs);
        params.put("imgStr", jsonArray.toJSONString());
//        params.put("imgStr", imgStrs.get(0));


        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    showMessage("图片上传成功");
                    EventBus.getDefault().post("", "updateRuKuChengGongJiLu");

                } else {
                    showMessage("图片上传失败");

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

                ArmsUtils.makeText(getContext(), content);

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());

    }
}
